﻿using System;
using System.Collections.Generic;
using MySql.Data.MySqlClient;

namespace FWPDocumentation.Common.DbTools
{
    public class SqlCommand
    {
        private MySqlCommand _command;

        public string CommandText
        {
            get { return _command.CommandText; }
            set { _command.CommandText = value; }
        }

        public SqlCommand(string commandText)
        {
            _command = new MySqlCommand { Connection = DbIface.Connection };
            CommandText = commandText;
        }

        public T ExecuteScalar<T>() where T : new()
        {
			var result = _command.ExecuteScalar();
			return result == null ? TypeTools.GetDefaultValue<T>() : (T) result;
        }

        public void ExecuteNonQuery()
        {
            _command.ExecuteNonQuery();
        }

        public List<T> ExecuteQuery<T>() where T : new()
        {
            var resultList = new List<T>();
            if (string.IsNullOrWhiteSpace(CommandText))
            {
                return resultList;
            }
            var reader = _command.ExecuteReader();
            while (reader.Read())
            {
                var currentRow = (T)Activator.CreateInstance(typeof(T));
                var propertiesInfo = currentRow.GetType().GetProperties();
                foreach (var prop in propertiesInfo)
                {
                    prop.SetValue(currentRow, Convert.ChangeType(reader[prop.Name], prop.PropertyType), null);
                }
                resultList.Add(currentRow);
            }
	        reader.Close();
            return resultList;
        }
    }
}
